$(function () {
    // 页面发起请求就就服务器 查询所有菜品分类信息并且把数据绑定到下拉选项框
    $.ajax({
        type: "get",
        url: "http://192.168.1.30:8080/dishCategory/all",
        // 将页面输入的值变成json格式
        dataType:"json",
        // ajax发起请求以后返回的结果集在msg
        success: function (msg) {
            console.log(msg);
            $.each(msg.date.list, function (i, n) {
                // 把数据库结果集的值绑定到页面上
                var op = $("<option value=" + n.id + ">" + n. dishCategoryName + "</option>");
                $("#dishCategory").append(op);
            })
        }
    });

    $("#saveDish").click(function () {
        var dish_name = $("#dish_name").val();
        var dishCategory = $("#dishCategory").find("option:selected").attr("value");
        var price = $("#price").val();
        // 用户输入的值不能为空
        if (dish_name == "") {
            alert("菜品名称不能为空");
            // 代码不能继续往下走
            return;
        }
        if (dishCategory == 0) {
            alert("菜品分类未选择");
            return;
        }
        if (price == "") {
            alert("菜品价格不能为空");
            return;
        }

        var json = {
            "dishName":dish_name,
            "price":price,
            "picPath":"dklmmv fdlk.jpg",
            "category":{
                "id":dishCategory
            }
        }
        $.ajax({
            type: "post",
            url: "http://192.168.1.30:8080/dish/addDish",
            dataType:"json",
            data: JSON.stringify(json),
            contentType:"application/json;charset=UTF-8",
            success: function (msg) {
                if (msg.code == 200) {
                    alert("添加菜品成功");
                } else {
                    alert(msg.message);
                }
                // 不管成功失败都要去页面展示菜品信息
                window.location.href = "./showDishes.html";
            }
        });
    })
    // 添加菜品类
    $(".dishesCategory>button").click(function(){
        var dishCategoryName = prompt("请输入您要添加的菜品名称");
        $.ajax({
            type: "post",
            url: "http://192.168.1.30:8080/dishCategory",
            data: "op=addDishCategory&dishesCategoryName="+dishCategoryName,
            success: function (msg) {
              var json = JSON.parse(msg);
              console.log(json);
            }
        });
    })
})